package TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Server {
    private static final HashMap<String,String> hashMap = new HashMap<>();
    public void start(Socket socket){
        try {
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();

            DataInputStream dis = new DataInputStream(is);
            DataOutputStream dos = new DataOutputStream(os);

            while (true) {
                try {
                    //读数据
                    String str = dis.readUTF();
                    //进行转化且响应回客户端
                    putData();
                    String ret = process(str);
                    if (ret == null){
                        ret = "输出错误!!!";
                    }
                    System.out.println(socket.getRemoteSocketAddress()+"发送的消息为:" + ret);
                    dos.writeUTF(ret);
                    dos.flush();
                } catch (IOException e) {
                    System.out.println(socket.getRemoteSocketAddress()+" 已下线了!!!!");
                    dos.close();
                    dis.close();
                    socket.close();
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void putData(){
        hashMap.put("狗","dog");
        hashMap.put("猪","pig");
        hashMap.put("鱼","fish");
        hashMap.put("鸟","bird");
        hashMap.put("鸭","duck");
    }
    private static String process(String str){
        return hashMap.get(str);
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
/*            Socket socket = serverSocket.accept();
            System.out.println(socket.getRemoteSocketAddress()+" 上线啦!!!!");
            Server server = new Server();
            new Thread(() -> server.start(socket)).start();*/

            Socket socket = serverSocket.accept();
            System.out.println(socket.getRemoteSocketAddress() + " 上线啦!!!");
            Server server = new Server();

            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.submit(() -> server.start(socket));
        }

    }
}
